package cn.liccshop.sys.utils;

import cn.liccshop.core.entity.ShopOrderInfo;
import cn.liccshop.core.service.shopOrderInfo.mapper.ShopOrderInfoMapper;
import cn.liccshop.core.service.shopOrderInfo.service.IShopOrderInfoService;
import cn.liccshop.sys.cache.CommonCacheUtil;
import cn.liccshop.sys.constants.Constants;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LiCC
 * @program LiCCShop
 * @description 未支付订单定时器
 * @since 2019-05-28-02:29
 */
@Slf4j
@Component
public class OrderSchedulingUtil {
    @Autowired
    private CommonCacheUtil cacheUtil;
    @Autowired
    private IShopOrderInfoService orderInfoService;
    @Scheduled(fixedRate =  3600000)
    public void orderPayCountDown(){
        /** 获取未支付的订单 **/
        List<ShopOrderInfo> orderInfos = orderInfoService.list(new QueryWrapper<>(new ShopOrderInfo().setOrderStatus(Constants.ORDER_STATUS_PAY)));
        /** 存储需要取消的订单 **/
        List<ShopOrderInfo> updatorderInfos = new ArrayList<>();
        for (ShopOrderInfo orderInfo : orderInfos){
            /** 遍历未支付订单 **/
            /** 通过订单ID查询订单是否过期 **/
            boolean overdue = cacheUtil.getCacheOrderPayCountDown(orderInfo.getId());
            if (!overdue){
                /** 订单过期 存储订单ID 和订单失效状态 **/
                updatorderInfos.add(new ShopOrderInfo().setId(orderInfo.getId()).setOrderStatus(Constants.ORDER_STATUS_CANCEL));
            }
        }
        if (CollectionUtils.isNotEmpty(updatorderInfos)){
            /** 过期订单存在 通过订单ID批量修改状态 **/
            orderInfoService.updateBatchById(updatorderInfos);
        }
    }
}
